package com.example.sicnuaccountingapp.data.dao

import androidx.room.*
import com.example.sicnuaccountingapp.data.entity.Category
import kotlinx.coroutines.flow.Flow
import com.example.sicnuaccountingapp.data.entity.TransactionType

@Dao
interface CategoryDao {
    @Insert
    suspend fun insertCategory(category: Category): Long

    @Insert
    suspend fun insertCategories(categories: List<Category>)

    @Update
    suspend fun update(category: Category)

    @Delete
    suspend fun delete(category: Category)

    @Query("SELECT * FROM categories WHERE userId = :userId")
    fun getAllCategories(userId: Long): Flow<List<Category>>

    @Query("SELECT * FROM categories WHERE userId = :userId AND type = :type ORDER BY sortOrder ASC")
    fun getCategoriesByType(userId: Long, type: TransactionType): Flow<List<Category>>

    @Query("SELECT * FROM categories WHERE categoryId = :categoryId")
    suspend fun getCategoryById(categoryId: Long): Category?

    @Query("SELECT MAX(sortOrder) FROM categories WHERE userId = :userId AND type = :type")
    suspend fun getMaxSortOrder(userId: Long, type: TransactionType): Int?

    @Query("SELECT * FROM categories WHERE userId = :userId")
    suspend fun getCategoriesByUserId(userId: Long): List<Category>

    @Transaction
    suspend fun updateCategoryOrder(categories: List<Category>) {
        categories.forEachIndexed { index, category ->
            update(category.copy(sortOrder = index))
        }
    }
} 